package com.open.capacity.license;

import com.open.capacity.utils.encrypt.DESHelper;
import com.open.capacity.utils.file.FileUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.text.MessageFormat;

/**
 * License生成类
 *
 * @author zifangsky
 * @date 2018/4/19
 * @since 1.0.0
 */
public class LicenseCreator {
    private static Logger logger = LogManager.getLogger(LicenseCreator.class);


    private String machineCode;

    public LicenseCreator(String machineCode) {
        this.machineCode = machineCode;
    }

    /**
     * 生成License证书
     *
     * @return boolean
     * @author zifangsky
     * @date 2018/4/20 10:58
     * @since 1.0.0
     */
    public boolean generateLicense(String licensePath, String licenseCode) {
        try {
            if (!DESHelper.encrypt(machineCode).equals(licenseCode)) {
                logger.error(MessageFormat.format("授权失败：授权码无效", machineCode));
                return false;
            }

            FileUtils.fileLinesWrite(licensePath, licenseCode, false);
            return true;
        } catch (Exception e) {
            logger.error(MessageFormat.format("授权码生成失败：{0}", machineCode), e);
            return false;
        }
    }


    /**
     * 生成License证书
     *
     * @return boolean
     * @author zifangsky
     * @date 2018/4/20 10:58
     * @since 1.0.0
     */
    public String getLicense() {
        String license = "";
        try {
            license = DESHelper.encrypt(machineCode);
        } catch (Exception e) {
            logger.error(MessageFormat.format("授权码生成失败：{0}", machineCode), e);
        }
        return license;
    }
}
